"""
估值分析智能体

基于Agno框架实现的估值分析智能体，负责对股票进行估值分析，
包括DCF估值、相对估值、PEG分析等多种估值方法。
"""

import logging
from typing import Dict, Any, Optional
from agno.agent import Agent
from ..utils.model_factory import create_model

from ..tools.akshare_client import AkShareClient
from ..tools.llm_client import LLMClient
from ..models.analysis_results import ValuationAnalysis

logger = logging.getLogger(__name__)


class ValuationAnalystAgent:
    """估值分析智能体"""
    
    def __init__(self, model_id: str = "deepseek-chat"):
        """
        初始化估值分析智能体
        
        Args:
            model_id: LLM模型ID
        """
        self.model_id = model_id
        self.akshare_client = AkShareClient()
        self.llm_client = LLMClient()
        
        def analyze_valuation(agent: Agent, ticker: str, analysis_period: str = "annual") -> str:
            """
            进行综合估值分析

            Args:
                agent: Agno智能体实例
                ticker: 股票代码
                analysis_period: 分析周期 (annual/quarterly)

            Returns:
                str: 估值分析结果
            """
            try:
                logger.info(f"开始对股票 {ticker} 进行专业估值分析")

                # 获取财务数据
                # financial_data = self.akshare_client.get_financial_indicators(ticker)
                import json
                import os
                from ..models.market_data import FinancialMetrics, MarketData

                data_dir = "data/collected_data"
                filename = f"market_data_agent_data_{ticker}_latest.json"
                file_path = os.path.join(data_dir, filename)
                with open(file_path, "r") as f:
                    collected_data = json.load(f)

                financial_metrics_dict = collected_data.get("summary", {}).get("financial_data", {})
                financial_metrics = FinancialMetrics(**financial_metrics_dict)

                # 获取市场价值
                market_cap = getattr(financial_metrics, 'market_cap', 0) if financial_metrics else 0
                if market_cap <= 0:
                    return "❌ 无法获取有效的市场价值数据"

                # 提取关键财务数据
                net_income = getattr(financial_metrics, 'net_income', 0)
                depreciation = getattr(financial_metrics, 'depreciation_and_amortization', 0)
                capex = getattr(financial_metrics, 'capital_expenditure', 0)

                # 计算营运资金变化（简化处理）
                working_capital_change = getattr(financial_metrics, 'working_capital', 0) - getattr(financial_metrics, 'previous_working_capital', 0)

                earnings_growth = getattr(financial_metrics, 'earnings_growth', 0.05) or 0.05

                # 1. 所有者收益法估值（巴菲特方法）
                owner_earnings_result = self._calculate_owner_earnings_value(
                    net_income=net_income,
                    depreciation=depreciation,
                    capex=capex,
                    working_capital_change=working_capital_change,
                    growth_rate=earnings_growth,
                    required_return=0.15,
                    margin_of_safety=0.25
                )

                free_cash_flow = getattr(financial_metrics, 'free_cash_flow', 0)
                # 2. DCF估值
                dcf_result = self._calculate_dcf_value(
                    free_cash_flow=free_cash_flow,
                    growth_rate=earnings_growth,
                    discount_rate=0.10
                )
                

                # 3. 使用双重验证逻辑
                valuation_analysis = self._generate_professional_valuation_analysis(
                    ticker=ticker,
                    market_cap=market_cap,
                    owner_earnings_result=owner_earnings_result,
                    dcf_result=dcf_result,
                    financial_data=financial_metrics
                )

                if "valuation_analysis" not in agent.session_state:
                    agent.session_state["valuation_analysis"] = {}

                # 存储到智能体状态
                agent.session_state["valuation_analysis"][ticker] = {
                    "market_cap": market_cap,
                    "owner_earnings_analysis": owner_earnings_result,
                    "dcf_analysis": dcf_result,
                    "analysis": valuation_analysis,
                    # "analysis_period": analysis_period 
                }

                # 记录执行日志
                agent.session_state["execution_logs"].append({
                    "action": "professional_valuation_analysis",
                    "ticker": ticker,
                    "timestamp": self.akshare_client._get_current_time(),
                    "status": "completed"
                })

                return valuation_analysis

            except Exception as e:
                error_msg = f"专业估值分析失败: {str(e)}"
                logger.error(error_msg)
                return f"❌ {error_msg}"
        
        # def calculate_dcf_valuation(agent: Agent, ticker: str, growth_rate: float = 0.05, discount_rate: float = 0.10) -> str:
        #     """
        #     计算DCF估值 - 简化版本，调用专业估值分析
        #     """
        #     try:
        #         logger.info(f"计算股票 {ticker} 的DCF估值")

        #         # 直接调用综合估值分析，避免重复代码
        #         return self.analyze_valuation(agent, ticker)

        #     except Exception as e:
        #         error_msg = f"DCF估值计算失败: {str(e)}"
        #         logger.error(error_msg)
        #         return f"❌ {error_msg}"
        
        def calculate_relative_valuation(agent: Agent, ticker: str, peer_group: Optional[list] = None) -> str:
            """
            计算相对估值 - 简化版本，提供基础对比
            """
            try:
                logger.info(f"计算股票 {ticker} 的相对估值")

                # 获取基础财务数据
                financial_data = self.akshare_client.get_financial_indicators(ticker)
                market_data = self.akshare_client.get_stock_info(ticker)

                if not financial_data:
                    return "❌ 无法获取财务数据，相对估值分析失败"

                # 计算基础估值指标
                basic_metrics = self._calculate_basic_valuation_metrics(financial_data, market_data)

                # 生成简化的相对估值报告
                report = f"""📈 **{ticker} 相对估值分析**

    **基础估值指标**：
    - 市盈率 (PE): {basic_metrics.get('pe_ratio', 'N/A')}
    - 市净率 (PB): {basic_metrics.get('pb_ratio', 'N/A')}
    - 市销率 (PS): {basic_metrics.get('ps_ratio', 'N/A')}
    - 净资产收益率 (ROE): {basic_metrics.get('roe', 'N/A')}%

    **估值水平评估**：
    - 财务健康度评分: {basic_metrics.get('financial_health_score', 0)}/3

    **投资建议**：基于基础指标的相对估值分析，建议结合专业估值分析获得更准确的投资建议。
    """

                # 存储结果
                if ticker not in agent.session_state["valuation_data"]:
                    agent.session_state["valuation_data"][ticker] = {}

                agent.session_state["valuation_data"][ticker]["relative_valuation"] = basic_metrics

                return report

            except Exception as e:
                error_msg = f"相对估值计算失败: {str(e)}"
                logger.error(error_msg)
                return f"❌ {error_msg}"
        
        def get_valuation_summary(agent: Agent, ticker: str) -> str:
            """
            获取估值分析摘要
            
            Args:
                agent: Agno智能体实例
                ticker: 股票代码
                
            Returns:
                str: 估值摘要
            """
            try:
                valuation_data = agent.session_state["valuation_data"].get(ticker, {})
                
                if not valuation_data:
                    return f"❌ 未找到股票 {ticker} 的估值数据，请先进行估值分析"
                
                # 生成综合估值摘要
                summary = self._generate_valuation_summary(ticker, valuation_data)
                
                return f"""
                **{ticker} 估值分析摘要**
                
                {summary}
                
                **风险提示**：估值分析基于历史数据和假设，实际投资需谨慎考虑市场风险。
                """
                
            except Exception as e:
                error_msg = f"生成估值摘要失败: {str(e)}"
                logger.error(error_msg)
                return f"❌ {error_msg}"

        # 初始化Agno智能体
        self.agent = Agent(
            name="Valuation Analyst Agent",
            role="专业的股票估值分析师，精通各种估值方法和财务建模",
            model=create_model(model_id),
            tools=[
                analyze_valuation,
                # calculate_dcf_valuation, 暂时不使用
                # calculate_relative_valuation, 暂时不使用
                get_valuation_summary
            ],
            session_state={
                "valuation_data": {},
                "analysis_results": {},
                "execution_logs": []
            },
            instructions="""
            你是一位资深的股票估值分析师，具备以下专业能力：

            1. **估值方法掌握**：
               - DCF（现金流折现）估值模型
               - 相对估值法（PE、PB、PS、EV/EBITDA等）
               - PEG分析和成长性估值
               - 资产基础估值法

            2. **分析框架**：
               - 收集和分析财务数据
               - 评估公司内在价值
               - 比较市场价格与内在价值
               - 提供买入/卖出/持有建议

            3. **风险评估**：
               - 识别估值风险因素
               - 敏感性分析
               - 情景分析

            4. **报告要求**：
               - 提供清晰的估值结论
               - 说明估值方法和假设
               - 给出目标价格区间
               - 评估投资价值

            请始终基于数据和专业分析提供客观的估值意见。
            """,
            add_state_in_messages=True,
            show_tool_calls=True,
            markdown=True
        )
        
        logger.info("估值分析智能体初始化完成")

    def _calculate_basic_valuation_metrics(self, financial_data: Any, market_data: Any) -> Dict[str, Any]:
        """计算基础估值指标 - 简化版本"""
        try:
            metrics = {}

            # 获取基础数据
            current_price = getattr(market_data, 'current_price', 0) if market_data else 0
            market_cap = getattr(market_data, 'market_cap', 0) if market_data else 0

            # 从财务数据获取关键指标
            eps = getattr(financial_data, 'earnings_per_share', 0) if financial_data else 0
            revenue = getattr(financial_data, 'revenue', 0) if financial_data else 0
            net_income = getattr(financial_data, 'net_income', 0) if financial_data else 0
            book_value = getattr(financial_data, 'book_value_per_share', 0) if financial_data else 0
            roe = getattr(financial_data, 'return_on_equity', 0) if financial_data else 0

            # 计算核心估值指标
            # 1. PE比率 (市盈率)
            if eps and eps > 0 and current_price > 0:
                metrics["pe_ratio"] = round(current_price / eps, 2)
            else:
                metrics["pe_ratio"] = None

            # 2. PB比率 (市净率)
            if book_value and book_value > 0 and current_price > 0:
                metrics["pb_ratio"] = round(current_price / book_value, 2)
            else:
                metrics["pb_ratio"] = None

            # 3. PS比率 (市销率)
            if revenue and revenue > 0 and market_cap > 0:
                metrics["ps_ratio"] = round(market_cap / revenue, 2)
            else:
                metrics["ps_ratio"] = None

            # 4. ROE (净资产收益率)
            if roe:
                metrics["roe"] = round(roe * 100, 2) if roe < 1 else round(roe, 2)
            else:
                metrics["roe"] = None

            # 5. 基础财务健康度评分
            health_score = 0
            if metrics.get("pe_ratio") and 5 <= metrics["pe_ratio"] <= 25:
                health_score += 1
            if metrics.get("pb_ratio") and 0.5 <= metrics["pb_ratio"] <= 3:
                health_score += 1
            if metrics.get("roe") and metrics["roe"] > 10:
                health_score += 1

            metrics["financial_health_score"] = health_score

            logger.info("基础估值指标计算完成")
            return metrics

        except Exception as e:
            logger.error(f"计算基础估值指标失败: {e}")
            return {
                "pe_ratio": None,
                "pb_ratio": None,
                "ps_ratio": None,
                "roe": None,
                "financial_health_score": 0
            }
    
    def _calculate_dcf_value(self, free_cash_flow: float, growth_rate: float, discount_rate: float) -> Dict[str, Any]:
        """计算DCF价值"""
        try:
            if free_cash_flow <= 0:
                return {"dcf_value": 0, "error": f"自由现金流为负值 ({free_cash_flow:,.0f})，DCF估值不适用"}

            # 专业DCF计算方法
            dcf_value = self._calculate_intrinsic_value_professional(
                free_cash_flow=free_cash_flow,
                growth_rate=growth_rate,
                discount_rate=discount_rate,
                terminal_growth_rate=0.03,
                num_years=5
            )

            return {
                "dcf_value": dcf_value,
                "free_cash_flow": free_cash_flow,
                "growth_rate": growth_rate,
                "discount_rate": discount_rate,
                "terminal_growth_rate": min(growth_rate * 0.4, 0.03)
            }

        except Exception as e:
            logger.error(f"DCF估值计算失败: {e}")
            return {"dcf_value": 0, "error": f"DCF估值计算失败: {str(e)}"}

    def _calculate_intrinsic_value_professional(
        self,
        free_cash_flow: float,
        growth_rate: float = 0.05,
        discount_rate: float = 0.10,
        terminal_growth_rate: float = 0.02,
        num_years: int = 5,
    ) -> float:
        """
        使用DCF方法计算内在价值
         Args:
        free_cash_flow: 自由现金流
        growth_rate: 预期增长率
        discount_rate: 基础折现率
        terminal_growth_rate: 永续增长率
        num_years: 预测年数

        Returns:
            float: 计算得到的内在价值
        """
        try:
            if not isinstance(free_cash_flow, (int, float)) or free_cash_flow <= 0:
                return 0

            # 调整增长率，确保合理
            growth_rate = min(max(growth_rate, 0), 0.25)  # 限制在0-25%之间

            # 调整永续增长率，不能超过经济平均增长
            terminal_growth_rate = min(growth_rate * 0.4, 0.03)  # 取增长率的40%或3%的较小值

            # 计算预测期现金流现值
            present_values = []
            for year in range(1, num_years + 1):
                future_cf = free_cash_flow * (1 + growth_rate) ** year
                present_value = future_cf / (1 + discount_rate) ** year
                present_values.append(present_value)

            # 计算永续价值
            terminal_year_cf = free_cash_flow * (1 + growth_rate) ** num_years
            terminal_value = terminal_year_cf * (1 + terminal_growth_rate) / (discount_rate - terminal_growth_rate)
            terminal_present_value = terminal_value / (1 + discount_rate) ** num_years

            # 总价值
            total_value = sum(present_values) + terminal_present_value

            return max(total_value, 0)  # 确保不返回负值

        except Exception as e:
            logger.error(f"专业DCF计算错误: {e}")
            return 0

    def _calculate_owner_earnings_value(
        self,
        net_income: float,
        depreciation: float,
        capex: float,
        working_capital_change: float,
        growth_rate: float = 0.05,
        required_return: float = 0.15,
        margin_of_safety: float = 0.25,
        num_years: int = 5
    ) -> Dict[str, Any]:
        """
        使用所有者收益法计算公司价值（巴菲特方法）
        """
        try:
            # 数据有效性检查
            if not all(isinstance(x, (int, float)) for x in [net_income, depreciation, capex, working_capital_change]):
                return {"owner_earnings_value": 0, "error": "财务数据不完整"}

            # 计算初始所有者收益
            owner_earnings = (
                net_income +
                depreciation -
                capex -
                working_capital_change
            )

            if owner_earnings <= 0:
                return {"owner_earnings_value": 0, "error": f"所有者收益为负值 ({owner_earnings:,.0f})"}

            # 调整增长率，确保合理性
            growth_rate = min(max(growth_rate, 0), 0.25)  # 限制在0-25%之间

            # 计算预测期收益现值
            future_values = []
            for year in range(1, num_years + 1):
                # 使用递减增长率模型
                year_growth = growth_rate * (1 - year / (2 * num_years))  # 增长率逐年递减
                future_value = owner_earnings * (1 + year_growth) ** year
                discounted_value = future_value / (1 + required_return) ** year
                future_values.append(discounted_value)

            # 计算永续价值
            terminal_growth = min(growth_rate * 0.4, 0.03)  # 永续增长率取增长率的40%或3%的较小值
            terminal_value = (future_values[-1] * (1 + terminal_growth)) / (required_return - terminal_growth)
            terminal_value_discounted = terminal_value / (1 + required_return) ** num_years

            # 计算总价值并应用安全边际
            intrinsic_value = sum(future_values) + terminal_value_discounted
            value_with_safety_margin = intrinsic_value * (1 - margin_of_safety)

            return {
                "owner_earnings_value": max(value_with_safety_margin, 0),
                "owner_earnings": owner_earnings,
                "intrinsic_value_before_margin": intrinsic_value,
                "safety_margin": margin_of_safety,
                "required_return": required_return
            }

        except Exception as e:
            logger.error(f"所有者收益计算错误: {e}")
            return {"owner_earnings_value": 0, "error": f"所有者收益计算失败: {str(e)}"}

    def _generate_professional_valuation_analysis(
        self,
        ticker: str,
        market_cap: float,
        owner_earnings_result: Dict[str, Any],
        dcf_result: Dict[str, Any],
        financial_data: Any
    ) -> str:
        """
        生成专业估值分析报告
        """
        try:
            # 获取估值结果
            owner_earnings_value = owner_earnings_result.get("owner_earnings_value", 0)
            dcf_value = dcf_result.get("dcf_value", 0)

            # 计算估值缺口
            dcf_gap = (dcf_value - market_cap) / market_cap if market_cap > 0 else 0
            owner_earnings_gap = (owner_earnings_value - market_cap) / market_cap if market_cap > 0 else 0
            valuation_gap = (dcf_gap + owner_earnings_gap) / 2

            # 生成投资信号
            if valuation_gap > 0.10:  # 10%低估
                signal = 'bullish'
                signal_desc = "买入"
            elif valuation_gap < -0.20:  # 20%高估
                signal = 'bearish'
                signal_desc = "卖出"
            else:
                signal = 'neutral'
                signal_desc = "持有"

            # 计算置信度
            confidence = abs(valuation_gap)

            # 生成专业分析报告
            report = f"""**{ticker} 专业估值分析报告**

**投资信号**: {signal_desc.upper()} ({signal})
**置信度**: {confidence:.1%}
**估值缺口**: {valuation_gap:+.1%}

**双重估值验证**:

**1. 所有者收益法 (巴菲特方法)**:
"""

            if owner_earnings_result.get("error"):
                report += f"   ❌ {owner_earnings_result['error']}\n"
            else:
                owner_earnings = owner_earnings_result.get("owner_earnings", 0)
                safety_margin = owner_earnings_result.get("safety_margin", 0.25)
                report += f"""   - 所有者收益: {owner_earnings:,.0f} 万元
   - 估值结果: {owner_earnings_value:,.0f} 万元
   - 安全边际: {safety_margin:.1%}
   - 估值缺口: {owner_earnings_gap:+.1%}
   - 信号: {'看涨' if owner_earnings_gap > 0.10 else '看跌' if owner_earnings_gap < -0.20 else '中性'}
"""

            report += f"""
**2. DCF现金流折现法**:
"""

            if dcf_result.get("error"):
                report += f"   ❌ {dcf_result['error']}\n"
            else:
                free_cash_flow = dcf_result.get("free_cash_flow", 0)
                growth_rate = dcf_result.get("growth_rate", 0)
                discount_rate = dcf_result.get("discount_rate", 0)
                report += f"""   - 自由现金流: {free_cash_flow:,.0f} 万元
   - 增长率假设: {growth_rate:.1%}
   - 折现率: {discount_rate:.1%}
   - 估值结果: {dcf_value:,.0f} 万元
   - 估值缺口: {dcf_gap:+.1%}
   - 信号: {'看涨' if dcf_gap > 0.10 else '看跌' if dcf_gap < -0.20 else '中性'}
"""

            report += f"""
**3. 市场对比**:
   - 当前市值: {market_cap:,.0f} 万元
   - 所有者收益估值: {owner_earnings_value:,.0f} 万元
   - DCF估值: {dcf_value:,.0f} 万元
   - 平均内在价值: {(owner_earnings_value + dcf_value) / 2:,.0f} 万元

**4. 投资建议**:
"""

            # 生成投资建议
            if signal == 'bullish':
                report += f"""   **强烈推荐买入**
   - 理由: 双重估值法显示股票被低估{abs(valuation_gap):.1%}
   - 预期收益: 具有{abs(valuation_gap):.1%}的上涨空间
   - 风险提示: 注意市场波动风险"""
            elif signal == 'bearish':
                report += f"""   **建议卖出**
   - 理由: 双重估值法显示股票被高估{abs(valuation_gap):.1%}
   - 风险提示: 存在{abs(valuation_gap):.1%}的下跌风险
   - 操作建议: 考虑减仓或退出"""
            else:
                report += f"""   **建议持有**
   - 理由: 估值水平相对合理
   - 估值区间: 在合理估值范围内
   - 操作建议: 保持现有仓位，关注基本面变化"""

            report += f"""

**5. 分析方法说明**:
   - 所有者收益法: 巴菲特推崇的估值方法，考虑实际现金收益
   - DCF折现法: 基于未来现金流的内在价值计算
   - 双重验证: 两种方法结合，提高估值准确性
   - 安全边际: 内置25%安全边际，降低投资风险

**重要提示**: 本分析基于历史财务数据，投资需谨慎考虑市场风险和公司基本面变化。
"""

            logger.info(f"专业估值分析报告生成完成: {ticker}")
            return {"report": report, "signal": signal, "confidence": confidence}

        except Exception as e:
            logger.error(f"生成专业估值分析失败: {e}")
            return f"❌ 生成专业估值分析失败: {str(e)}"


    
    def _generate_valuation_summary(self, ticker: str, valuation_data: Dict) -> str:
        """生成估值摘要"""
        try:
            if not valuation_data:
                return "❌ 估值数据不足，无法生成摘要"

            summary = f"""
**{ticker} 综合估值分析摘要**

"""

            # 1. 基本估值指标摘要
            if 'valuation_metrics' in valuation_data:
                metrics = valuation_data['valuation_metrics']
                summary += "**核心估值指标**：\n"

                if metrics.get('pe_ratio'):
                    pe_level = "合理" if 10 <= metrics['pe_ratio'] <= 25 else ("偏低" if metrics['pe_ratio'] < 10 else "偏高")
                    summary += f"- 市盈率 (PE): {metrics['pe_ratio']:.1f} ({pe_level})\n"

                if metrics.get('pb_ratio'):
                    pb_level = "合理" if 1 <= metrics['pb_ratio'] <= 3 else ("偏低" if metrics['pb_ratio'] < 1 else "偏高")
                    summary += f"- 市净率 (PB): {metrics['pb_ratio']:.1f} ({pb_level})\n"

                if metrics.get('ps_ratio'):
                    summary += f"- 市销率 (PS): {metrics['ps_ratio']:.1f}\n"

                if metrics.get('roe'):
                    roe_level = "优秀" if metrics['roe'] > 15 else ("良好" if metrics['roe'] > 10 else "一般")
                    summary += f"- 净资产收益率 (ROE): {metrics['roe']:.1f}% ({roe_level})\n"

                summary += "\n"

            # 2. DCF估值摘要
            if 'dcf_valuation' in valuation_data:
                summary += "**DCF估值分析**：\n"
                dcf_data = valuation_data['dcf_valuation']
                if isinstance(dcf_data, str) and "企业总价值" in dcf_data:
                    # 提取企业价值（简化处理）
                    summary += "- DCF模型显示企业具有内在价值\n"
                    summary += "- 基于现金流折现的估值方法\n"
                else:
                    summary += "- DCF估值计算完成\n"
                summary += "\n"

            # 3. 相对估值摘要
            if 'relative_valuation' in valuation_data:
                summary += "**相对估值分析**：\n"
                rel_data = valuation_data['relative_valuation']
                if isinstance(rel_data, str):
                    if "高估" in rel_data:
                        summary += "- 相对同行业：估值偏高\n"
                    elif "低估" in rel_data:
                        summary += "- 相对同行业：估值偏低\n"
                    else:
                        summary += "- 相对同行业：估值合理\n"
                summary += "- 已与同行业公司进行对比分析\n"
                summary += "\n"

            # 4. 综合评估
            summary += "**综合投资建议**：\n"

            # 基于可用数据生成建议
            recommendations = []
            risks = []

            if 'valuation_metrics' in valuation_data:
                metrics = valuation_data['valuation_metrics']

                # PE分析
                if metrics.get('pe_ratio'):
                    if metrics['pe_ratio'] < 10:
                        recommendations.append("PE较低，可能存在价值投资机会")
                    elif metrics['pe_ratio'] > 30:
                        risks.append("PE较高，估值风险需要关注")

                # ROE分析
                if metrics.get('roe'):
                    if metrics['roe'] > 15:
                        recommendations.append("ROE表现优秀，盈利能力强")
                    elif metrics['roe'] < 8:
                        risks.append("ROE偏低，盈利能力有待提升")

                # PB分析
                if metrics.get('pb_ratio'):
                    if metrics['pb_ratio'] < 1:
                        recommendations.append("PB低于1，资产价值被低估")
                    elif metrics['pb_ratio'] > 5:
                        risks.append("PB较高，需关注资产泡沫风险")

            # 生成建议
            if recommendations:
                summary += "**投资亮点**：\n"
                for rec in recommendations:
                    summary += f"- {rec}\n"
                summary += "\n"

            if risks:
                summary += "**风险提示**：\n"
                for risk in risks:
                    summary += f"- {risk}\n"
                summary += "\n"

            # 总体建议
            summary += "**总体评级**：\n"

            # 简化的评级逻辑
            positive_signals = len(recommendations)
            risk_signals = len(risks)

            if positive_signals > risk_signals:
                if positive_signals >= 2:
                    summary += "- 评级：**买入** \n"
                    summary += "- 理由：多项指标显示投资价值\n"
                else:
                    summary += "- 评级：**增持** \n"
                    summary += "- 理由：基本面表现良好\n"
            elif risk_signals > positive_signals:
                summary += "- 评级：**谨慎** \n"
                summary += "- 理由：存在一定估值风险\n"
            else:
                summary += "- 评级：**持有** \n"
                summary += "- 理由：估值水平相对合理\n"

            summary += "\n**分析说明**：\n"
            summary += "- 本分析基于历史财务数据和市场信息\n"
            summary += "- 投资决策需结合市场环境和个人风险偏好\n"
            summary += "- 建议持续关注公司基本面变化\n"

            logger.info("估值摘要生成完成")
            return summary

        except Exception as e:
            logger.error(f"生成估值摘要失败: {e}")
            return f"❌ 生成估值摘要失败: {str(e)}"
    
    def run(self, message: str, **kwargs) -> str:
        """运行智能体"""
        try:
            response = self.agent.run(message, **kwargs)
            # 正确处理RunResponse对象
            if response:
                if hasattr(response, 'content'):
                    return str(response.content) if response.content else "执行失败，未收到响应内容"
                else:
                    return str(response) if response else "执行失败，响应为空"
            else:
                return "执行失败，未收到响应"
        except Exception as e:
            logger.error(f"智能体运行失败: {str(e)}")
            return f"❌ 智能体运行失败: {str(e)}"
    
    def print_response(self, message: str, stream: bool = False, **kwargs):
        """打印智能体响应"""
        try:
            if stream:
                self.agent.print_response(message, stream=True, **kwargs)
            else:
                response = self.run(message, **kwargs)
                print(response)
        except Exception as e:
            logger.error(f"打印响应失败: {str(e)}")
            print(f"❌ 打印响应失败: {str(e)}")

    def get_analysis_result(self, ticker: str) -> Optional[Dict[str, Any]]:
        """获取估值分析结果"""
        return self.agent.session_state.get("valuation_analysis", {}).get(ticker)
